#include "common.h"

Propeller propeller = {0,0};
Battery_data battery_data = {0, 0, 0};
Aipov_Data aipov_data = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Depth_data depth_data = {0,0,0,0};
float height = 0;
nlohmann::json j;

int set_uart(int fd, int speed, int bits, char check, int stop) {
    struct termios newtio, oldtio;
 
    // 步骤一：保存原来的串口配置
    if(tcgetattr(fd, &oldtio) != 0) {
        printf("tcgetattr oldtio error\n");
        return -1;
    }
    
    bzero(&newtio, sizeof(newtio));
    
    // 步骤二：设置控制模式标志
    newtio.c_cflag |= CLOCAL | CREAD;
    newtio.c_cflag &= ~CSIZE;
 
    // 步骤三：设置数据位
    switch(bits) {
        case 7:
            newtio.c_cflag |= CS7;
            break;
        case 8:
            newtio.c_cflag |= CS8;
            break;
    }
    
    // 步骤四：设置奇偶校验位
    switch(check) {
        case 'O': // 偶校验位
            newtio.c_cflag |= PARENB;
            newtio.c_cflag |= PARODD;
            newtio.c_iflag |= (INPCK | ISTRIP);
            break;
        case 'E': // 奇校验位
            newtio.c_cflag |= PARENB;
            newtio.c_cflag &= ~PARODD;
            newtio.c_iflag |= (INPCK | ISTRIP);
            break;
        case 'N': // 无校验
            newtio.c_cflag &= ~PARENB;
            break;
    }
    
    // 步骤五：设置波特率
    switch(speed) {
        case 9600:
            cfsetispeed(&newtio, B9600);
            cfsetospeed(&newtio, B9600);
            break;
        case 38400:
            cfsetispeed(&newtio, B38400);
            cfsetospeed(&newtio, B38400);
            break;
        case 115200:
            cfsetispeed(&newtio, B115200);
            cfsetospeed(&newtio, B115200);
            break;
    }
    
    // 步骤六：设置停止位
    switch(stop) {
        case 1:
            newtio.c_cflag &= ~CSTOPB; // 1位停止位
            break;
        case 2:
            newtio.c_cflag |= CSTOPB; // 2位停止位
            break;
    }
    
    // 步骤七：刷新输入队列
    tcflush(fd, TCIFLUSH);
    
    // 步骤八：设置配置立刻生效
    if (tcsetattr(fd, TCSANOW, &newtio) != 0) {
        printf("tcsetattr newtio error\n");
        return -2;
    }
    
    return 0;
}

void handleMessage(const string& message) {
    cout << "Received: " << message << endl;
}

void format(char *buf,char *buffer){
    buffer[0] = 0xFE;
    buffer[1] = 0xFE;
    buffer[BUFFER_SIZE-1] = 0xFD;
    buffer[BUFFER_SIZE-2] = 0xFD;

    for(int i = 0;i < 70;i++){
        buffer[i+2] = buf[i];
    }

    char num = buffer[0];

    for(int i = 1;i < 72;i++){
        num ^= buffer[i]; 
    }

    buffer[72] = num;

    return ;
}

// 计算从起始点(start_x, start_y)到目标点(end_x, end_y)的角度
double calculate_angle(double start_x, double start_y, double end_x, double end_y) {
    double dx = end_x - start_x;
    double dy = end_y - start_y;
    
    // 使用atan2函数计算角度，结果为弧度
    double angle_rad = atan2(dy, dx);
    
    // 确保角度在0到2π之间
    if (angle_rad < 0) {
        angle_rad += 2 * PI;
    }
    
    return angle_rad;
}

// 计算两点间的欧几里得距离
double calculate_distance(double x1, double y1, double x2, double y2) {
    double dx = x2 - x1;
    double dy = y2 - y1;
    
    return sqrt(dx * dx + dy * dy);
}

// 序列化单个数据项
void serialize_item(void *dest, const void *src, size_t size, int *offset) {
    char* dest_char = static_cast<char*>(dest);
    const char* src_char = static_cast<const char*>(src);
    memcpy(dest_char + *offset, src_char, size);
    *offset += size;

    // memcpy(dest + *offset, src, size);
    // *offset += size;
}

int Limit_Size(int out, int max, int min){
    if(out < max && out > min){
        propeller.angle = out;
    }else if(out >= max){
        propeller.angle = max;
    }else if(out <= min){
        propeller.angle = min;
    }

    return out;
}

// 获取当前时间
string getCurrentTime() {
    // 获取当前时间
    time_t now = time(nullptr);
    // 转换为本地时间
    tm* ltm = localtime(&now);

    // 格式化时间字符串
    char buffer[80];
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ltm);

    string result(buffer);
    replace(result.begin(), result.end(), ':', '_'); // 替换冒号为短横线

    return result;
}

// 函数：写入CSV文件
void writeCSV(const string& filename, const vector<vector<string>>& data) {
    ofstream file(filename,ios::app);

    if (!file.is_open()) {
        cerr << "无法打开文件: " << filename << endl;
        return;
    }

    for (const auto& row : data) {
        for (size_t i = 0; i < row.size(); ++i) {
            file << row[i];
            if (i < row.size() - 1) {
                file << ",";
            }
        }
        file << "\n";
    }

    file.close();
}

void print_resp(unsigned char *data, int n){
    for(int i=0;i<n;i++){
        printf("<0x%02x> ",data[i]);
    }
    printf("\n");
}


